<?php

namespace app\adminapi\controller;

use app\model\UsersModel;
use support\Redis;
use Webman\Http\Request;

class User extends BaseAdminApi
{
    /**
     * 不需要登录的方法
     * @var array
     */
    protected $noNeedLogin = ['wechatLogin'];

    /**
     * 不需要权限验证的方法（已登录但不验证具体权限）
     * @var array
     */
    protected $noNeedPermission = [];

    /**
     * 获取用户列表
     */
    public function getUsers(Request $request)
    {
        $params = $request->get();
        $pageSize = $params['pageSize'] ?? 10;

        $query = UsersModel::query();

        // 搜索条件
        if (!empty($params['username'])) {
            $query->where('username', 'like', '%' . $params['username'] . '%');
        }

        if (!empty($params['nickname'])) {
            $query->where('nickname', 'like', '%' . $params['nickname'] . '%');
        }



        if (!empty($params['email'])) {
            $query->where('email', 'like', '%' . $params['email'] . '%');
        }

        if (isset($params['status']) && $params['status'] !== '') {
            $query->where('status', $params['status']);
        }

        if (!empty($params['login_type'])) {
            $query->where('login_type', $params['login_type']);
        }

        if (!empty($params['gender']) && $params['gender'] !== '0') {
            $query->where('gender', $params['gender']);
        }

        $paginate = $query->orderBy('created_at', 'desc')
            ->paginate($pageSize);

        return dataByPage($paginate);
    }

    /**
     * 保存用户
     */
    public function saveUser(Request $request)
    {
        $params = $request->post();

        $rules = [
            'nickname' => 'required|max:50',

            'email' => 'nullable|email|max:100',
            'gender' => 'nullable|in:0,1,2',
            'birthday' => 'nullable|date',
            'status' => 'required|in:0,1'
        ];

        $messages = [
            'nickname.required' => '昵称不能为空',
            'nickname.max' => '昵称不能超过50个字符',

            'email.email' => '邮箱格式不正确',
            'email.max' => '邮箱不能超过100个字符',
            'gender.in' => '性别值只能是0、1或2',
            'birthday.date' => '生日格式不正确',
            'status.required' => '状态不能为空',
            'status.in' => '状态值只能是0或1'
        ];

        // 如果提供了用户名和密码，则验证
        if (!empty($params['username']) || !empty($params['password'])) {
            $rules['username'] = 'required|min:4|max:50';
            $rules['password'] = ['required', 'min:6', 'regex:/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]+$/'];
            $messages['username.required'] = '用户名不能为空';
            $messages['username.min'] = '用户名至少4个字符';
            $messages['username.max'] = '用户名不能超过50个字符';
            $messages['password.required'] = '密码不能为空';
            $messages['password.min'] = '密码至少6个字符';
            $messages['password.regex'] = '密码必须包含字母、数字和特殊字符';
        }

        // 编辑时密码可选
        if (isset($params['id']) && !empty($params['id']) && !empty($params['password'])) {
            $rules['password'] = ['min:6', 'regex:/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]+$/'];
            $messages['password.min'] = '密码至少6个字符';
            $messages['password.regex'] = '密码必须包含字母、数字和特殊字符';
        }

        $validator = validator($params, $rules, $messages);

        if ($validator->fails()) {
            return fail($validator->errors()->first());
        }

        try {
            if (isset($params['id']) && !empty($params['id'])) {
                // 编辑用户
                $user = UsersModel::find($params['id']);
                if (!$user) {
                    return fail('用户不存在');
                }

                // 检查用户名是否重复（排除自己）
                if (!empty($params['username'])) {
                    $existUser = UsersModel::where('username', $params['username'])
                        ->where('id', '!=', $params['id'])
                        ->first();
                    if ($existUser) {
                        return fail('用户名已存在');
                    }
                }



                // 检查邮箱是否重复（排除自己）
                if (!empty($params['email'])) {
                    $existEmail = UsersModel::where('email', $params['email'])
                        ->where('id', '!=', $params['id'])
                        ->first();
                    if ($existEmail) {
                        return fail('邮箱已存在');
                    }
                }

                $updateData = [
                    'nickname' => $params['nickname'],

                    'email' => $params['email'] ?? null,
                    'gender' => $params['gender'] ?? 0,
                    'birthday' => $params['birthday'] ?? null,
                    'status' => $params['status']
                ];

                // 如果提供了用户名，则更新
                if (!empty($params['username'])) {
                    $updateData['username'] = $params['username'];
                    $updateData['login_type'] = 'username';
                }

                // 如果提供了新密码，则更新密码
                if (!empty($params['password'])) {
                    $updateData['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
                }

                $user->update($updateData);

                return success('用户更新成功');
            } else {
                // 新增用户
                $userData = [
                    'id' => randomString(),
                    'nickname' => $params['nickname'],

                    'email' => $params['email'] ?? null,
                    'gender' => $params['gender'] ?? 0,
                    'birthday' => $params['birthday'] ?? null,
                    'status' => $params['status'],
                    'login_type' => 'username'
                ];

                // 如果提供了用户名和密码
                if (!empty($params['username']) && !empty($params['password'])) {
                    // 检查用户名是否重复
                    $existUser = UsersModel::where('username', $params['username'])->first();
                    if ($existUser) {
                        return fail('用户名已存在');
                    }
                    
                    $userData['username'] = $params['username'];
                    $userData['password'] = password_hash($params['password'], PASSWORD_DEFAULT);
                }



                // 检查邮箱是否重复
                if (!empty($params['email'])) {
                    $existEmail = UsersModel::where('email', $params['email'])->first();
                    if ($existEmail) {
                        return fail('邮箱已存在');
                    }
                }

                UsersModel::create($userData);

                return success('用户创建成功');
            }
        } catch (\Exception $e) {
            return fail('操作失败：' . $e->getMessage());
        }
    }

    /**
     * 删除用户
     */
    public function deleteUser(Request $request)
    {
        $params = $request->post();

        if (!isset($params['id']) || empty($params['id'])) {
            return fail('请提供要删除的用户ID');
        }

        try {
            $user = UsersModel::find($params['id']);
            if (!$user) {
                return fail('用户不存在');
            }

            // 删除用户
            $user->delete();

            return success('用户删除成功');
        } catch (\Exception $e) {
            return fail('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 微信登录
     */
    public function wechatLogin(Request $request)
    {
        $params = $request->post();

        $validator = validator($params, [
            'code' => 'required',
            'login_type' => 'required|in:wechat,wechat_mp'
        ], [
            'code.required' => '授权码不能为空',
            'login_type.required' => '登录类型不能为空',
            'login_type.in' => '登录类型只能是wechat或wechat_mp'
        ]);

        if ($validator->fails()) {
            return fail($validator->errors()->first());
        }

        try {
            // 这里需要根据实际的微信API来获取用户信息
            // 示例代码，实际需要调用微信API
            $wechatData = [
                'openid' => 'mock_openid_' . time(),
                'nickname' => $params['nickname'] ?? '微信用户',
                'avatarUrl' => $params['avatarUrl'] ?? null,
                'gender' => $params['gender'] ?? 0,
                'unionid' => $params['unionid'] ?? null
            ];

            // 创建或更新用户
            $user = UsersModel::createOrUpdateWechatUser($wechatData, $params['login_type']);

            // 生成token
            $token = randomString();
            $ttl = 3600 * 24 * 7; // 七天

            Redis::setex($token, $ttl, $user->id);

            return data([
                'token' => $token,
                'user' => $user
            ]);
        } catch (\Exception $e) {
            return fail('登录失败：' . $e->getMessage());
        }
    }

    /**
     * 用户名密码登录
     */
    public function login(Request $request)
    {
        $params = $request->post();

        $validator = validator($params, [
            'username' => 'required',
            'password' => 'required'
        ], [
            'username.required' => '用户名不能为空',
            'password.required' => '密码不能为空'
        ]);

        if ($validator->fails()) {
            return fail($validator->errors()->first());
        }

        try {
            $user = UsersModel::findByLoginType($params['username'], 'username');

            if (!$user) {
                return fail('用户不存在');
            }

            if ($user->status != 1) {
                return fail('用户已被禁用');
            }

            if (!password_verify($params['password'], $user->password)) {
                return fail('密码错误');
            }

            // 更新登录信息
            $user->update([
                'last_login_time' => date('Y-m-d H:i:s'),
                'last_login_ip' => $request->getRealIp()
            ]);

            // 生成token
            $token = randomString();
            $ttl = 3600 * 24 * 7; // 七天

            Redis::setex($token, $ttl, $user->id);

            return data([
                'token' => $token,
                'user' => $user
            ]);
        } catch (\Exception $e) {
            return fail('登录失败：' . $e->getMessage());
        }
    }

    /**
     * 禁用/启用用户
     */
    public function toggleUserStatus(Request $request)
    {
        $params = $request->post();

        if (!isset($params['id']) || empty($params['id'])) {
            return fail('请提供用户ID');
        }

        if (!isset($params['status']) || !in_array($params['status'], [0, 1])) {
            return fail('状态值只能是0或1');
        }

        try {
            $user = UsersModel::find($params['id']);
            if (!$user) {
                return fail('用户不存在');
            }

            $user->update(['status' => $params['status']]);

            $statusText = $params['status'] == 1 ? '启用' : '禁用';
            return success('用户' . $statusText . '成功');
        } catch (\Exception $e) {
            return fail('操作失败：' . $e->getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo(Request $request)
    {
        $token = $request->header('authorization');
        
        if (!$token) {
            return fail('请先登录', 401);
        }

        $userId = Redis::get($token);
        
        if (!$userId) {
            return fail('登录已过期', 401);
        }

        $user = UsersModel::find($userId);
        
        if (!$user) {
            return fail('用户不存在', 401);
        }

        return data($user);
    }
}